package com.wnnight.wys.web.menu;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.wnnight.wys.entity.menu.Menu;
import com.wnnight.wys.security.JwtUtils;
import com.wnnight.wys.service.menu.MenuService;
import com.wnnight.wys.vo.ResultVo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.List;

/**
 * @ClassName: MenuController
 * @Description: //TODO
 * @author: CHX42
 * @date: 2022/9/9-10:27
 * @version: v1.0
 */
@RestController
@RequestMapping("/api/v1/menu")
@Slf4j
@Transactional
public class MenuController {
    @Autowired
    private MenuService menuService;

    @PostMapping("/list")
    public ResultVo<?> MenuList(HttpServletRequest request) {
        QueryWrapper<Menu> menuWrapper = new QueryWrapper<>();
        String jwt = request.getHeader("jwt");
        Object roleId = JwtUtils.getInfo(jwt, "roleId");
        String[] menuType = {"m", "c"};
        menuWrapper.in("wys_menu.menu_type", menuType);
        menuWrapper.eq("wys_role_menu.role_id", roleId);
        menuWrapper.orderByAsc("wys_menu.order_num");
        List<Menu> menuList = menuService.menuPage(new Page<>(1, Integer.MAX_VALUE), menuWrapper).getRecords();
        List<Menu> menuBack = new ArrayList<>();
        for (Menu menu : menuList) {
            if (menu.getParentId() == 0) {
                List<Menu> menus = new ArrayList<>();
                for (Menu menu_temp : menuList) {
                    if (menu_temp.getParentId().equals(menu.getId())) {
                        menus.add(menu_temp);
                    }
                    menu.setSubMenu(menus);
                }
                menuBack.add(menu);
            }
        }
        return new ResultVo<>(menuBack);
    }
}
